export function objectToQueryString(obj: Record<string, any>) {
    const keyValuePairs = Object.keys(obj).map(key => {
        const value = (obj[key] instanceof Object) && (JSON.stringify(obj[key])) || obj[key];
        return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
    });
    return keyValuePairs.join('&');
}

type LOG_TYPE = "elem_show" | "elem_click";
interface SendLogParams {
    targetId: string
    logType: LOG_TYPE
    extraJson?: Record<string, any>
}

class Logger {
    private url: string;

    constructor(options: { url: string }) {
        this.url = options.url;
    }

    async sendLog(options: SendLogParams) {
        return new Promise((resolve, reject) => {
            const image = new Image();
            image.src = `${this.url}?${objectToQueryString(options)}`;
            image.onload = event => {
                resolve(event);
            }
            image.onerror = err => {
                reject(err);
            }
        });
    }
}

export default Logger;

export const logger = new Logger({
    url: import.meta.env.VITE_LOG_URL
});
